#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2022/4/7 10:12 上午
# @Author : wang
# @Email : 136697880@qq.com
# @File : account.py
# @Project : bugmgr
import random

from django.core.exceptions import ValidationError
from django_redis import get_redis_connection

from utils.sms import SendSms
from django import forms
from django.core.validators import RegexValidator
from django.conf import settings
from web import models
from utils import encrypt
from bootstrap import BootStrap

class UserInfoForm(BootStrap, forms.ModelForm):
    password = forms.CharField(label='密码', min_length=8, max_length=32,
                               error_messages={'min_length': "密码长度不能小于8", 'max_length': "密码长度不能大于32"},
                               widget=forms.PasswordInput)
    confirmPassword = forms.CharField(label='重复密码', min_length=8, max_length=32,
                                      error_messages={'min_length': "密码长度不能小于8", 'max_length': "密码长度不能大于32"},
                                      widget=forms.PasswordInput)
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'mail', 'password', 'confirmPassword', 'phone', 'code']



    def clean_username(self):
        username = self.cleaned_data['username']
        if models.UserInfo.objects.filter(username=username).exists():
            raise ValidationError('用户名已存在')
        return username

    def clean_mail(self):
        mail = self.cleaned_data['mail']
        if models.UserInfo.objects.filter(mail=mail).exists():
            raise ValidationError('邮箱已存在')
        return mail

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if models.UserInfo.objects.filter(phone=phone).exists():
            raise ValidationError('手机号已存在')
        return phone

    def clean_password(self):
        password = self.cleaned_data['password']
        return encrypt.md5(password)

    def clean_confirmPassword(self):
        password = self.cleaned_data.get('password')
        confirmPassword = encrypt.md5(self.cleaned_data['confirmPassword'])
        if password != confirmPassword:
            raise ValidationError('两次密码不一致')
        return confirmPassword

    def clean_code(self):
        code = self.cleaned_data['code']
        redis_conn = get_redis_connection('default')
        redis_code = redis_conn.get(self.cleaned_data.get('phone'))
        print(code)
        print(redis_code)

        if redis_code is None:
            raise ValidationError('验证码已过期')
        if code != redis_code.decode():
            print('验证码不正确')
            raise ValidationError('验证码错误')

        return code


class LoginForm(BootStrap, forms.Form):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')])
    code = forms.CharField(label='验证码',widget=forms.TextInput(attrs={'class':'form-control'}))


class SendsmsForm(BootStrap, forms.Form):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')])

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

        """手机号校验的钩子函数"""

    def clean_phone(self):
        phone = self.cleaned_data['phone']
        if models.UserInfo.objects.filter(phone=phone).exists():
            raise ValidationError('手机号已经存在')

        # 发短信 并写入redis
        code = random.randrange(1000, 9999)
        print('code:', code)
        MS = settings.MS
        result = SendSms.SendSms(phone, MS.format(code))
        # 写入redis
        conn = get_redis_connection('default')
        conn.set(phone, code, ex=60)

        return phone

    # 判断模板是否存在
    # tpl = self.request.GET.get('tpl')
    # template_id = settings.TENCENT_SMS_TEMPLATE_ID.get(tpl)
    # if not template_id:
    #     raise forms.ValidationError('模板不存在')
